<template>
  <view class="card-container">
    <!-- 名片主体 -->
    <view class="card-view">
      <!-- 头像与基本信息 -->
      <view class="card-header">
        <image 
          class="avatar" 
          :src="cardInfo.avatar || defaultAvatar" 
          mode="widthFix"
          alt="用户头像"
        ></image>
        <view class="user-info">
          <view class="name">{{ cardInfo.name || '未设置' }}</view>
          <view class="position">{{ cardInfo.position || '未设置' }}</view>
          <view class="company">{{ cardInfo.company || '未设置' }}</view>
        </view>
      </view>

      <!-- 联系方式 -->
      <view class="contact-info">
        <view class="contact-item" v-if="cardInfo.phone">
          <view class="label">电话</view>
          <view class="value">{{ cardInfo.phone }}</view>
        </view>
        <view class="contact-item" v-if="cardInfo.wechat">
          <view class="label">微信</view>
          <view class="value">{{ cardInfo.wechat }}</view>
        </view>
        <view class="contact-item" v-if="cardInfo.email">
          <view class="label">邮箱</view>
          <view class="value">{{ cardInfo.email }}</view>
        </view>
        <view class="contact-item" v-if="cardInfo.address">
          <view class="label">地址</view>
          <view class="value">{{ cardInfo.address }}</view>
        </view>
      </view>

      <!-- 交换按钮 -->
      <button 
         v-if="showExchangeBtn"
        class="exchange-btn"
        @click="handleExchangeRequest"
      >
        交换名片
      </button>
    </view>

    <!-- 交换请求弹窗 -->
    <!-- <view class="modal" v-if="showRequestModal"> -->
      <view class="modal-content">
        <view class="modal-title">名片交换请求</view>
        <view class="request-info">
          <image 
            class="req-avatar" 
            :src="currentUser.avatar || defaultAvatar" 
            mode="widthFix"
            alt="当前用户头像"
          ></image>
          <view class="req-name">{{ currentUser.name || '用户' }}</view>
          <view class="req-msg">想与您交换名片</view>
        </view>
        <view class="modal-btns">
          <button class="cancel-btn" @click="handleCancel">拒绝</button>
          <button class="confirm-btn" @click="handleConfirm">同意</button>
        </view>
      </view>
    <!-- </view> -->

    <!-- 加载提示 -->
    <view class="loading" v-if="loading">
      <view class="loading-spinner"></view>
      <view class="loading-text">{{ loadingText }}</view>
    </view>

    <!-- 提示信息 -->
    <view class="toast" v-if="showToast">
      {{ toastMessage }}
    </view>
  </view>
</template>

<script>
import {
  ref,
  reactive,
  onMounted,
  computed
} from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import defaultAvatar from '@/static/default-avatar.png'

export default {
  setup() {
    // 响应式数据
    // const cardInfo = ref({})
    const currentUser = ref({})
    const exchangedList = ref([])
    const requestId = ref('')
	
	// 预览数据
	const cardInfo = {
		name: '张三default',
		title: '总经理',
		company: '深圳市惠森信息科技有限公司',
		phone: '15013869352',
		email: 'asdf@test.com',
		address: '同乐村',
		avatar: 'https://picsum.photos/id/1005/200/200',
		qrcode: 'https://picsum.photos/id/237/100/100'
	}
    
    // 状态管理
    const loading = ref(false)
    const loadingText = ref('')
    const showToast = ref(false)
    const toastMessage = ref('')
    const showRequestModal = ref(false)
    const defaultAvatarUrl = ref(defaultAvatar)
    
    // 路由参数
    const routeParams = ref({})
    
    // 计算属性：是否显示交换按钮
    const showExchangeBtn = computed(() => {
      // return cardInfo._openid && currentUser.openid && 
      //        cardInfo._openid !== currentUser.openid &&
      //        !exchangedList.value.includes(cardInfo._id)
	  return true
    })
    
    // 显示提示信息
    const showToastMessage = (msg, duration = 2000) => {
      toastMessage.value = msg
      showToast.value = true
      setTimeout(() => {
        showToast.value = false
      }, duration)
    }
    
    // 显示加载提示
    const showLoading = (text = '处理中...') => {
      loadingText.value = text
      loading.value = true
    }
    
    // 隐藏加载提示
    const hideLoading = () => {
      loading.value = false
    }
    
    // 获取当前用户信息
    const getCurrentUser = async () => {
      try {
        const res = await uni.cloud.callFunction({
          name: 'getCurrentUser'
        })
        if (res.result.code === 0) {
          Object.assign(currentUser, res.result.data)
        }
      } catch (err) {
        console.error('获取当前用户信息失败', err)
      }
    }
    
    // 获取名片详情
    const getCardDetail = async (id) => {
      try {
        showLoading('加载名片中...')
        const res = await uni.cloud.callFunction({
          name: 'getCardDetail',
          data: { id }
        })
        
        if (res.result.code === 0) {
          Object.assign(cardInfo, res.result.data)
        } else {
          showToastMessage('获取名片失败')
        }
        hideLoading()
      } catch (err) {
        console.error('获取名片详情失败', err)
        hideLoading()
        showToastMessage('获取名片失败')
      }
    }
    
    // 获取已交换列表
    const getExchangedList = async () => {
      try {
        const res = await uni.cloud.callFunction({
          name: 'getExchangedList'
        })
        if (res.result.code === 0) {
          exchangedList.value = res.result.data.map(item => item.target_card_id)
        }
      } catch (err) {
        console.error('获取已交换列表失败', err)
      }
    }
    
    // 发送交换请求
    const handleExchangeRequest = async () => {
      if (!currentUser.openid) {
        showToastMessage('请先登录')
        return
      }
      
      try {
        showLoading('发送请求中...')
        const res = await uni.cloud.callFunction({
          name: 'sendExchangeRequest',
          data: {
            targetOpenid: cardInfo._openid,
            targetCardId: cardInfo._id,
            senderInfo: {
              name: currentUser.name,
              avatar: currentUser.avatar,
              cardId: currentUser.cardId,
              position: currentUser.position
            }
          }
        })
        
        hideLoading()
        if (res.result.code === 0) {
          requestId.value = res.result.requestId
          showToastMessage('交换请求已发送')
        } else {
          showToastMessage(res.result.msg || '发送请求失败')
        }
      } catch (err) {
        console.error('发送交换请求失败', err)
        hideLoading()
        showToastMessage('发送请求失败')
      }
    }
    
    // 处理同意交换
    const handleConfirm = async () => {
      try {
        showLoading('处理中...')
        const res = await uni.cloud.callFunction({
          name: 'handleExchangeResponse',
          data: {
            requestId: requestId.value,
            action: 'confirm'
          }
        })
        
        hideLoading()
        showRequestModal.value = false
        
        if (res.result.code === 0) {
          exchangedList.value.push(cardInfo._id)
          showToastMessage('已同意交换')
        } else {
          showToastMessage(res.result.msg || '处理失败')
        }
      } catch (err) {
        console.error('处理同意交换失败', err)
        hideLoading()
        showToastMessage('处理失败')
      }
    }
    
    // 处理拒绝交换
    const handleCancel = async () => {
      try {
        showLoading('处理中...')
        const res = await uni.cloud.callFunction({
          name: 'handleExchangeResponse',
          data: {
            requestId: requestId.value,
            action: 'reject'
          }
        })
        
        hideLoading()
        showRequestModal.value = false
        
        if (res.result.code === 0) {
          showToastMessage('已拒绝交换')
        } else {
          showToastMessage(res.result.msg || '处理失败')
        }
      } catch (err) {
        console.error('处理拒绝交换失败', err)
        hideLoading()
        showToastMessage('处理失败')
      }
    }
    
    // 页面加载时
    onLoad((params) => {
      routeParams.value = params
      if (params.requestId) {
        requestId.value = params.requestId
        showRequestModal.value = false
      }
    })
    
    // 组件挂载时
    onMounted(async () => {
      await getCurrentUser()
      if (routeParams.value.id) {
        await getCardDetail(routeParams.value.id)
        await getExchangedList()
      }
    })
    
    return {
      cardInfo,
      currentUser,
      defaultAvatar: defaultAvatarUrl,
      showExchangeBtn,
      showRequestModal,
      loading,
      loadingText,
      showToast,
      toastMessage,
      handleExchangeRequest,
      handleConfirm,
      handleCancel
    }
  }
}
</script>

<style scoped>
.card-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.card-view {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20rpx;
}

.avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.user-info .name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.user-info .position,
.user-info .company {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.contact-info {
  padding: 10rpx 0;
}

.contact-item {
  display: flex;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.contact-item .label {
  width: 120rpx;
  color: #999;
}

.contact-item .value {
  flex: 1;
  color: #333;
  word-break: break-all;
}

.exchange-btn {
  margin-top: 30rpx;
  background-color: #07c160;
  color: white;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  width: 100%;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 600rpx;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
}

.modal-title {
  font-size: 34rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.request-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
}

.req-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-bottom: 15rpx;
}

.req-name {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.req-msg {
  font-size: 26rpx;
  color: #666;
}

.modal-btns {
  display: flex;
  gap: 20rpx;
}

.modal-btns button {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.confirm-btn {
  background-color: #07c160;
  color: white;
}

/* 加载提示 */
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1001;
}

.loading-spinner {
  width: 50rpx;
  height: 50rpx;
  border: 5rpx solid #eee;
  border-top-color: #07c160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15rpx;
}

.loading-text {
  background-color: rgba(0,0,0,0.7);
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

/* 提示框 */
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0,0,0,0.7);
  color: white;
  padding: 16rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  z-index: 1001;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
